import { AsyncStorage } from 'react-native'
import { createReducer, createActions } from 'reduxsauce'
import Immutable from 'seamless-immutable'

/* ------------- Types and Action Creators ------------- */

const { Types, Creators } = createActions({
  registerRequest: ['mobile','password','deviceId','longitude','latitude'],
  registerSuccess: ['payload'],
  registerFailure: ['errMsg'],
})

export const RegisterTypes = Types
export default Creators

/* ------------- Initial State ------------- */

export const INITIAL_STATE = Immutable({
  mobile: null,
  password: null,
  deviceId: null,
  fetching: null,
  payload: null,
  error: null,
  errMsg: null,
})

/* ------------- Reducers ------------- */

// request the data from an api
export const request = (state, { mobile, password, deviceId }) =>
  state.merge({ fetching: true, error:null,mobile, password,deviceId,payload:null,errMsg:null })

// successful api lookup
export const success = (state, action) => {
  const { payload } = action
  AsyncStorage.setItem('token', payload)
  return state.merge({ fetching: false, error: false, payload,errMsg:null })
}

// Something went wrong somewhere.
export const failure = (state, {errMsg}) =>
  state.merge({ fetching: false, error: true, payload: null, errMsg })

/* ------------- Hookup Reducers To Types ------------- */

export const reducer = createReducer(INITIAL_STATE, {
  [Types.REGISTER_REQUEST]: request,
  [Types.REGISTER_SUCCESS]: success,
  [Types.REGISTER_FAILURE]: failure
})
